<?php
/**
 * --------------------------------------------------------------
 * 文档控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Document as DocumentModel;
use app\admin\model\Column as ColumnModel;
use app\admin\model\Field as FieldModel;
use app\admin\model\DataModel as DataModelModel;
use util\Tree;
use think\Db;

class Document extends AdminBase
{
	/**
	 * 所有文档管理
	 */
	public function index()
	{
		cookie('__forward__', $_SERVER['REQUEST_URI']);
        
        $keyword      = input('param.keyword/s', '');
		$search_field = input('param.search_field/s', '');
		$cid          = input('param.cid/d', 0);
		$start_time   = input('param.start_time/s', '');
		$end_time     = input('param.end_time/s', '');
        
        $map = [];

        if ($search_field != '' && $keyword != '') {
            $map[] = ["document.".$search_field, 'like', "%{$keyword}%"];
        }
        if ($cid > 0) {
            $map[] = ['document.cid', '=', $cid];
        }
        if (!empty($start_time) && !empty($end_time) && $start_time == $end_time) {
            $map[] = ['document.create_time', '>=', strtotime($start_time." 00:00:00")];
            $map[] = ['document.create_time', '<=', strtotime($start_time." 23:59:59")];
        } else {
            if (!empty($start_time)) {
                $map[] = ['document.create_time', '>=', strtotime($start_time)];
            }
            if (!empty($end_time)) {
                $map[] = ['document.create_time', '<=', strtotime($end_time)];
            }
        }
        $conditions = [
            'cid'          => $cid,
            'start_time'   => $start_time,
            'end_time'     => $end_time,
            'keyword'      => $keyword,
            'search_field' => $search_field
        ];

    	$list = DocumentModel::view('document', true)
                ->view("column", 'title as column_title', 'column.id = document.cid', 'left')
                ->view("admin", 'adminname', 'admin.id = document.aid', 'left')
                ->where($map)
                ->order('document.update_time desc')
                ->paginate(config('app.site_setting.list_rows'), false, ['query' => $conditions]);
        
        // 获取非独立模型的相关栏目
        $marr = DataModelModel::where(['status' => 1, 'type' => [0,1]])->field('id')->select();
        $marr = $marr ? object_to_array($marr) : null;
        $marr = array_column($marr, 'id');
        $colmap = [
            'status'   => 1,
        ];
        if (!empty($marr)) $colmap['model_id'] = $marr;
        $columns = ColumnModel::where($colmap)->order('id asc,sort asc')->column('id,title,pid');
        $columns = $columns ? object_to_array($columns) : null;
        $columns = $columns ? Tree::toFormatTree($columns) : [];
        $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '请选择栏目')), $columns);
        
        $this->assign([
            'list'         => $list,
            'columns'      => $columns,
            'cid'          => $conditions['cid'],
            'start_time'   => $conditions['start_time'],
            'end_time'     => $conditions['end_time'],
            'keyword'      => $conditions['keyword'],
            'search_field' => $conditions['search_field'],
            'title'        => '所有文档列表'
        ]);
	    return $this->fetch();
	}
	
	/**
     * 新增文档
     * @param string $model_id 模型id
     * @return mixed
     */
    public function add($model_id = '')
    {
		if (empty($model_id)) return $this->error('参数错误');
	    if ($this->request->isAjax()) {
		    $DocumentModel = new DocumentModel();
            if (false === $DocumentModel->saveData()) {
                $this->error($DocumentModel->getError());
            }
            $this->success('新增成功', cookie('__forward__'));
		} else {
			$map = [
			    'model_id' => $model_id,
				'status'   => 1,
			];
            $columns = ColumnModel::where($map)->order('id asc,sort asc')->column('id,title,pid');
            $columns = $columns ? object_to_array($columns) : null;
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '请选择栏目')), $columns);
			$result  = [];
			if ($columns) foreach ($columns as $column) {
				$result[$column['id']] = $column['title_show'];
			}
			$columns = $result;
			
			// 独立模型只取该模型的字段，不包含系统字段
            if (get_model_type($model_id) == 2) {
                $where['model_id'] = $model_id;
            } else {
                $where['model_id'] = [0, $model_id];
            }
			
			// 获取文档模型字段
            $where['status'] = 1;
            $where['show']   = 1;
            $searchFields    = 'id,en_title as name,title,type,define,value,options,remark';
            $fields = FieldModel::where($where)->order('sort asc,id asc')->column($searchFields);
			
			foreach ($fields as &$value) {
                // 解析options
                if ($value['options'] != '') {
                    $value['options'] = parse_attr($value['options']);
                }
            }
			
			// 添加额外表单项信息
			$extra_field = [
				['name' => 'cid', 'title' => '所属栏目', 'type' => 'select', 'options' => $columns, 'value' => 0],
				['name' => 'model_id', 'type' => 'hidden', 'value' => $model_id]
			];
			$form_items = array_merge($extra_field, $fields);
			
			$this->assign([
				'form_items' => $form_items,
                'title'      => '新增'
			]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
	    if ($this->request->isPost()) {
			$DocumentModel = new DocumentModel();
            $result = $DocumentModel->saveData();
            if (false === $result) {
                $this->error($DocumentModel->getError());
            }
            $this->success('编辑成功', cookie('__forward__'));
		} else {
			// 获取数据
            $info = DocumentModel::getOne($id);
		    
			// 独立模型只取该模型的字段，不包含系统字段
			$where['model_id'] = [0, $info['model_id']];
			
			// 获取文档模型字段
			$where['status'] = 1;
			$where['show']   = 1;
            $searchFields    = 'id,en_title as name,title,type,define,value,options,remark';
            $fields = FieldModel::where($where)->order('sort asc,id asc')->column($searchFields);
			
			foreach ($fields as $id => &$value) {
				// 解析options
				if ($value['options'] != '') {
					$value['options'] = parse_attr($value['options']);
				}
				// 日期时间
				switch ($value['type']) {
					case 'date':
						$info[$value['name']] = format_time($info[$value['name']], 'Y-m-d');
						break;
					case 'time':
						$info[$value['name']] = format_time($info[$value['name']], 'H:i:s');
						break;
					case 'datetime':
						$info[$value['name']] = empty($info[$value['name']]) ? '' : format_time($info[$value['name']]);
						break;
				}
			}
			
			$map = [
			    'model_id' => $info['model_id'],
				'status'   => 1,
			];
            $columns = ColumnModel::where($map)->order('id asc,sort asc')->column('id,title,pid');
            $columns = $columns ? object_to_array($columns) : null;
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '请选择栏目')), $columns);
			$result  = [];
			if ($columns) foreach ($columns as $column) {
				$result[$column['id']] = $column['title_show'];
			}
			$columns = $result;
			
			// 添加额外表单项信息
			$extra_field = [
				['name' => 'id', 'type' => 'hidden'],
				['name' => 'cid', 'title' => '所属栏目', 'type' => 'select', 'options' => $columns],
				['name' => 'model_id', 'type' => 'hidden']
			];
			$form_items = array_merge($extra_field, $fields);
			
			foreach ($form_items as &$item) {
				if (isset($info[$item['name']])) {
					$item['value'] = $info[$item['name']];
				} else {
					$item['value'] = isset($item['value']) ? $item['value'] : '';
				}
            }

		    $this->assign([
                'id'         => $info['id'],
				'form_items' => $form_items,
				'title'      => '编辑'
			]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function delete($ids = 0, $table = '')
	{
        (int) $ids || $this->error('参数错误');
        $map  = ['id' => $ids];
		
		if ($table == '') {
            // 获取文档标题和模型id
            $data_list = DocumentModel::where('id', 'in', $ids)->column('id,model_id,title');

            foreach ($data_list as $document) {
                // 附加表名
                $extra_table = get_model_table($document['model_id']);

                // 删除附加表文档
                if (false === Db::table($extra_table)->where('doc_id', $document['id'])->delete()) {
                    $this->error('删除文档：'. $document['title']. ' 失败');
                }

                // 删除主表文档
                if (false === DocumentModel::where('id', $document['id'])->delete()) {
                    $this->error('删除失败');
                }
            }
        } else {
            // 删除独立文档
            if (false === Db::table($table)->where('doc_id', 'in', $ids)->delete()) {
                $this->error('删除失败');
            } else {
				// 删除基础文档
				DocumentModel::where('id', 'in', $ids)->delete();
			}
        }
        $this->success('删除成功');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = DocumentModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}